package com.taldh.algorithm.mutli.thread;

import lombok.SneakyThrows;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 交替打印奇偶数
 */
public class PrintAlternately {

    public static void main(String[] args) {
        打印偶数 printEven = new 打印偶数();
        打印奇数 printOdd = new 打印奇数();
        printEven.start();
        printOdd.start();
    }

    private static Object lock = new Object();

    private static volatile Integer count = 1;

    static class 打印偶数 extends Thread {
        @SneakyThrows
        @Override
        public void run() {
            synchronized (lock) {
                while (count <= 100) {
                    if (count % 2 == 0) {
                        System.out.println(count);
                        count ++ ;
                        lock.notify();
                    } else {
                        lock.wait();
                    }
                }
            }
        }
    }

    static class 打印奇数 extends Thread {
        @SneakyThrows
        @Override
        public void run() {
            synchronized (lock) {
                while (count <= 100) {
                    if (count % 2 != 0) {
                        System.out.println(count);
                        count ++ ;
                        lock.notify();
                    } else {
                        lock.wait();
                    }
                }
            }
        }
    }

}
